<?php

namespace App\Api\Controllers\YSEPay;


use \Illuminate\Support\Facades\Log;

class PayController
{

    private $domain = 'https://qrcode.ysepay.com';

    private $notifyUrl = 'https://kaifa.zgjindoufu.com/api/ysepay/pay_notify';

    private $YSEPayStoreID = '826361673720106';

    private $privateKeyPath = '../YSEPayUtil/client.pfx';//商户端的私钥证书 (RSA加密)
    private $publicKeyPath = '../YSEPayUtil/service.cer';//银盛端公钥证书 (RSA加密)

    private $keyPWD = 'Hh666888';//商户端私钥证书密码

    private function _exception($msg = '', $code = 0)
    {
        throw new \Exception($msg, $code);
    }

    private function curlPost($url, $params, $data, $timeout = 20)
    {
        $data['biz_content'] = json_encode($data['biz_content'], JSON_UNESCAPED_UNICODE);
        ksort($data);
        $pkcs12 = file_get_contents($this->privateKeyPath);
        if (!openssl_pkcs12_read($pkcs12, $certs, $this->keyPWD)) {
            $this->_exception("系统错误，请联系管理员");
        }
        $signStr = "";
        foreach ($data as $key => $val) {
            $signStr .= $key . '=' . $val . '&';
        }
        $http_query = rtrim($signStr, '&');
        if (!openssl_sign($http_query, $sign, $certs['pkey'], OPENSSL_ALGO_SHA1)) {
            $this->_exception("系统错误2，请联系管理员");
        }
        $sign = base64_encode($sign);
        $data['sign'] = rtrim($sign);
        $data = http_build_query($data, null, '&', PHP_QUERY_RFC3986);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $curlResponse = curl_exec($ch);
        $curlCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlMsg = curl_error($ch);
        curl_close($ch);
        if (!$curlResponse) {
            $this->_exception('curl请求失败：' . $curlMsg);
        }
        return $curlResponse;
    }

    public function __construct()
    {
        $this->privateKeyPath = app_path('Api/Controllers/YSEPay/YSEPayUtil/' . $this->privateKeyPath);
        $this->publicKeyPath = app_path('Api/Controllers/YSEPay/YSEPayUtil/' . $this->publicKeyPath);
    }

    //二维码支付
    public function QrCodePay($params = [], $data = [])
    {
        $current_time = time();
        $url = implode('/', [$this->domain, 'gateway.do']);
        $notifyUrl = $this->notifyUrl;
//        $notifyUrl = $notifyUrl . '?' . http_build_query($params);
        $result = $this->curlPost($url, [], [
            'method' => 'ysepay.online.qrcodepay',//Y 接口名称 固定值ysepay.online.qrcodepay
            'partner_id' => $this->YSEPayStoreID,//Y 在银盛支付开设的服务商商户号，请联系客户经理提供
            'timestamp' => date('Y-m-d H:i:s', $current_time),//Y 发送请求的时间，格式"yyyy-MM-dd HH:mm:ss" 2014-07-24 03:07:50
            'charset' => 'utf-8',//Y 商户网站使用的编码格式，如UTF-8、GBK、GB2312等，默认值 GBK
            'sign_type' => 'RSA',//Y 报文签名算法，RSA 、SM
            // 'sign' => '',//Y 签名字符串，再用Base64编码
            'notify_url' => $notifyUrl,//Y	交易成功异步通知到商户的后台地址，http路径支持多个url进行异步通知，多个url用分隔符“,”分开，格式如：url1,url2,url3，支持TLS1.0、TLS1.1、TLS1.2
            'version' => "3.5",//Y	版本号3.0/3.4/3.5 当前版本3.5
//            'return_url' => '',//N	（前台跳转）同步通知地址
//            'tran_type' => '',//N	交易类型，说明：1或者空：非担保交易，2：担保交易，无特殊需求 不用填此字段
            // 'tran_type' => 1,
            'biz_content' => $data,
        ]);
        $result = json_decode($result, true);
        if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
            $this->_exception('返回数据格式错误');
        }
        if ($result['ysepay_online_qrcodepay_response']['code'] != '10000' && $result['ysepay_online_qrcodepay_response']['msg'] != 'Success') {
            $this->_exception($result['ysepay_online_qrcodepay_response']['msg']);
        }
        return $result['ysepay_online_qrcodepay_response']['source_qr_code_url'];
    }


    public function BarCodePay($params = [], $data = [])
    {

        $current_time = time();
        $url = implode('/', [$this->domain, 'gateway.do']);
        $notifyUrl = $this->notifyUrl;
//        $notifyUrl = $notifyUrl . '?' . http_build_query($params);
        $result = $this->curlPost($url, [], [
            'method' => 'ysepay.online.barcodepay',//Y 接口名称 固定值ysepay.online.qrcodepay
            'partner_id' => $this->YSEPayStoreID,//Y 在银盛支付开设的服务商商户号，请联系客户经理提供
            'timestamp' => date('Y-m-d H:i:s', $current_time),//Y 发送请求的时间，格式"yyyy-MM-dd HH:mm:ss" 2014-07-24 03:07:50
            'charset' => 'utf-8',//Y 商户网站使用的编码格式，如UTF-8、GBK、GB2312等，默认值 GBK
            'sign_type' => 'RSA',//Y 报文签名算法，RSA 、SM
            // 'sign' => '',//Y 签名字符串，再用Base64编码
            'notify_url' => $notifyUrl,//Y	交易成功异步通知到商户的后台地址，http路径支持多个url进行异步通知，多个url用分隔符“,”分开，格式如：url1,url2,url3，支持TLS1.0、TLS1.1、TLS1.2
            'version' => "3.5",//Y	版本号3.0/3.4/3.5 当前版本3.5
//            'return_url' => '',//N	（前台跳转）同步通知地址
//            'tran_type' => '',//N	交易类型，说明：1或者空：非担保交易，2：担保交易，无特殊需求 不用填此字段
            // 'tran_type' => 1,
            'biz_content' => $data,
        ]);
        $result = json_decode($result, true);
        if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
            $this->_exception('返回数据格式错误');
        }
        if ($result['ysepay_online_qrcodepay_response']['code'] != '10000' && $result['ysepay_online_qrcodepay_response']['msg'] != 'Success') {
            $this->_exception($result['ysepay_online_qrcodepay_response']['msg']);
        }
        return $result['ysepay_online_qrcodepay_response']['source_qr_code_url'];
    }

    //订单查询
    public function OrderQuery($data)
    {
        $current_time = time();
        $url = implode('/', [$this->domain, 'gateway.do']);
        $result = $this->curlPost($url, [], [
            'method' => 'ysepay.online.trade.order.query',//Y 接口名称 固定值ysepay.online.qrcodepay
            'partner_id' => $this->YSEPayStoreID,//Y 在银盛支付开设的服务商商户号，请联系客户经理提供
            'timestamp' => date('Y-m-d H:i:s', $current_time),//Y 发送请求的时间，格式"yyyy-MM-dd HH:mm:ss" 2014-07-24 03:07:50
            'charset' => 'utf-8',//Y 商户网站使用的编码格式，如UTF-8、GBK、GB2312等，默认值 GBK
            'sign_type' => 'RSA',//Y 报文签名算法，RSA 、SM
            'version' => "3.5",//Y	版本号3.0/3.4/3.5 当前版本3.5
            'biz_content' => $data,
        ]);
        $result = json_decode($result, true);
        if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
            $this->_exception('返回数据格式错误');
        }
        Log::info('查询回调', $result);
        if (isset($result['sign']) && !$this->verifySign($result['sign'], $result['ysepay_online_trade_order_query_response'])) {
            $this->_exception("系统出错请联系管理员");
        }
        return $result['ysepay_online_trade_order_query_response'];
    }


}
